package edu.hnu.userserver.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Component
@RefreshScope
public class GlobalInterceptor implements HandlerInterceptor {

    @Value("${allow.secret}")
    String allowSecret;

    @Value("${only-through-gateway}")
    boolean onlyThroughGateway;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (onlyThroughGateway){
            String secretKey = request.getHeader("allow");
            if(secretKey==null || !secretKey.equals(allowSecret)){
                response.setContentType("application/json; charset=utf-8");
                PrintWriter writer = response.getWriter();
                writer.write("请通过网关访问");
                return false;
            }
        }
        return true;
    }
}
